/*
    Carracci Systems - Carracci Server (openbam project)
    Copyright (C) 2007  Carracci Systems

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/



package org.openbam.core.expr;

/**
 * @author inder
 */
public class TypeConvertor {

	/**
	 * Convert the object <code>o</code> to a Double. If <code>o</code> is
	 * <code>null</code>, then return <code> 0 - Double.valueOf(0.0)</code>.
	 * 
	 * @param o
	 * @return
	 */
	public static Double doubleValue(Object o) {
		if (o != null) {
			if (o instanceof Double) {
				return (Double) o;
			}
			if (o instanceof Number) {
				return Double.valueOf(((Number) o).doubleValue());
			}
			try {
				return Double.valueOf(o.toString());
			} catch (NumberFormatException e) {

			}
		}
		return Double.valueOf(0.0);
	}

	public static Integer integerValue(Object o) {
		if (o != null) {
			if (o instanceof Integer) {
				return (Integer) o;
			}
			if (o instanceof Number) {
				return Integer.valueOf(((Number) o).intValue());
			}
			try {
				return Integer.valueOf(o.toString());
			} catch (NumberFormatException e) {

			}
		}
		return Integer.valueOf(0);
	}

	public static Long longValue(Object o) {
		if (o != null) {
			if (o instanceof Long) {
				return (Long) o;
			}
			if (o instanceof Number) {
				return Long.valueOf(((Number) o).longValue());
			}
			try {
				return Long.valueOf(o.toString());
			} catch (NumberFormatException e) {

			}
		}
		return Long.valueOf(0L);
	}

	/**
	 * Convert an object to Boolean. The following rules are followed as part of
	 * this converstion:
	 * <li> if <code>o</code> is null return false.
	 * <li> if <code>o</code> is an instance of Boolean then return as is.
	 * <li> if the String representation of <code>o</code> (using
	 * {@link Object#toString()} is either <code>true</code> or
	 * <code>false</code>, then convert it to its appropriate boolean value -
	 * same as {@link {@link Boolean#valueOf(String)}. 
	 * <li> else return <code>false</code>
	 * <br>
	 * 
	 * @param o
	 * @return
	 */
	public static Boolean booleanValue(Object o) {
		if (o != null) {
			if (o instanceof Boolean) {
				return (Boolean) o;
			}
			return Boolean.valueOf(o.toString());
		}
		return Boolean.FALSE;
	}
}
